package org.dftproject.patml;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dftproject.genesis.core.data.flow.Collector;
import org.dftproject.genesis.data.genealogy.IPerson;
import org.dftproject.patml.data.PatmlPerson;

public class DataProvider extends org.dftproject.genesis.core.data.flow.DataProvider {
	
	public final static String ID = DataProvider.class.getName();
	
	private final static Pattern httpPattern = Pattern.compile("^https?://.*$");

	@Override
	public void getRelatedObjects(String uri, Collector<Object> collector) {
		try {
			collector.setProviderStatus(ID, true);
			
			// Have we been canceled since this job was scheduled?
			
			if (collector.isCanceled())
				return;

			// Is this an "http" URL?
				
			Matcher matcher = httpPattern.matcher(uri);
			if (matcher.matches()) {
				IPerson person = DataExtractor.getDefault().getPerson(uri);
				if (person != null)
					collector.addElement(person);
			}
		} finally {
			collector.setProviderStatus(ID, false);
		}
	}

	@Override
	public void getRelatedObjects(IPerson person, Collector<Object> collector) {
		try {
			collector.setProviderStatus(ID, true);
			
			// Have we been canceled since this job was scheduled?
			
			if (collector.isCanceled())
				return;

			if (person instanceof PatmlPerson) {
				PatmlPerson patmlPerson = (PatmlPerson) person;
				
				try {
					collector.addElement(new URL(patmlPerson.getSite().getPersonUrl(patmlPerson.getId())));
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace(System.err);
				}
			}
		} finally {
			collector.setProviderStatus(ID, false);
		}
	}

}
